/**
 * @Title: UserRealm.java
 * @Package shiro
 * @author zhanglinlu
 * @date 2019年4月23日 下午3:14:56
 */
package com.zll.ccp.shiro;

import com.zll.ccp.constants.Constant;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.zll.ccp.model.User;
import com.zll.ccp.service.ILoginService;

import java.util.Arrays;

/**
 * @ClassName: UserRealm
 * @Description: TODO
 * @author zhanglinlu
 * @date 2019年4月23日 下午3:14:56
 * 
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private ILoginService iservice;

    /* (non-Javadoc)
     * @param arg0
     * @return
     * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userName = (String) principalCollection.getPrimaryPrincipal();
        User user = iservice.getUserByUserName(userName);
        if (user != null && user.getAdmin() != null && StringUtils.equals(user.getAdmin(), Constant.ROLE_ADMIN)) {
            SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
            authorizationInfo.addRole(Constant.ROLE_ADMIN);
            return authorizationInfo;
        }
        return null;
    }

    /* (non-Javadoc)
     * @param arg0
     * @return
     * @throws AuthenticationException
     * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
        // 验证账号密码
        UsernamePasswordToken token = (UsernamePasswordToken)arg0;
        User user = iservice.getUserByUserName(token.getUsername());
        if (user == null) {
            return null;
        }
        AuthenticationInfo info =
            new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), this.getClass().getSimpleName());
        return info;
    }

}
